package com.bora_bandeco;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;

import com.actionbarsherlock.app.ActionBar;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class NovoConviteActivity extends SlidingFragmentActivity {

	public FragmentManager mFragmentManager;
	
	public static ConvidadosListAdapter adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.mFragmentManager = getSupportFragmentManager();

		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setCustomView(R.layout.actionbar);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setLogo(R.drawable.actionbar_logo);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setHomeButtonEnabled(true);

        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setBehindWidthRes(R.dimen.sliding_menu_width);
        slidingMenu.setBehindScrollScale(0.0f);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        setBehindContentView(R.layout.fragment_menu);
        
        
        setContentView(R.layout.activity_novo_convite);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_menu, new MenuFragment()).commit();
        
        //Esconde o ícone de notificação
        ImageView notification_icon = (ImageView)actionBar.getCustomView().findViewById(R.id.notification);
        notification_icon.setVisibility(View.GONE);
        
        Button novoContato = (Button) findViewById(R.id.novo_contato);
        novoContato.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				Intent intent;
    			intent = new Intent(arg0.getContext(), ContatosActivity.class);
    			startActivityForResult(intent, 0);
	        }
	    });
		
		NovoConviteActivity.adapter = new ConvidadosListAdapter(this);
		
		ExpandableHeightGridView grid = (ExpandableHeightGridView) findViewById(R.id.convidados);
		grid.setExpanded(true);
		grid.setAdapter(NovoConviteActivity.adapter);
		
		
		Button enviarConvite = (Button) findViewById(R.id.enviar_convite);
		enviarConvite.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				RadioGroup rg = (RadioGroup) findViewById(R.id.restaurante);
	            String restaurante = ((RadioButton)findViewById(rg.getCheckedRadioButtonId())).getText().toString();
	            
	            TimePicker tp = (TimePicker)findViewById(R.id.horario);

	            int ano = Calendar.getInstance().get(Calendar.YEAR);
	            int mes = Calendar.getInstance().get(Calendar.MONTH) + 1;
	            int dia = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
	            int hora = tp.getCurrentHour();
	            int minuto = tp.getCurrentMinute();
	            
	            SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	            long horario = 0;
				try {
					String dateStr = ano + "-" + mes + "-" + dia + " " + hora + ":" + minuto + ":00.000";
					Date date = sdf.parse(dateStr);
					
					// Se é referente a um horario anterior, mudar para o dia seguinte
					if (hora < Calendar.getInstance().get(Calendar.HOUR_OF_DAY) ||
						(hora == Calendar.getInstance().get(Calendar.HOUR_OF_DAY) && minuto <= Calendar.getInstance().get(Calendar.MINUTE))) {
						Calendar c = Calendar.getInstance();
						c.setTime(sdf.parse(dateStr));
						c.add(Calendar.DATE, 1);
						
						date = c.getTime();
					}
					horario = date.getTime();
				} catch (ParseException e) {
					// plis
				}
	            

				// Recupera o idContato do utilizador do aplicativo 
				// para ser enviado como "anfitrião" do convite
	            SharedPreferences prefs = getApplicationContext().getSharedPreferences("com.bora_bandeco", Context.MODE_PRIVATE);
	            int meuIdContato = prefs.getInt("_id", 0);
	            
	            // Recupera os contatos selecionados como convidados
	            List<Contato> convidados = NovoConviteActivity.adapter.getConvidados();
	            
	            // Realiza a requisição assíncrona do convite
	            ConviteSender sender = new ConviteSender(NovoConviteActivity.this, restaurante, horario, meuIdContato, convidados);
				sender.execute();
				
				// Mostra ícone de loading, esconde os outros elementos  
				// e no método onPostExecute, da classe ConviteSender, a activity é fechada
		        ImageView loaderView = (ImageView)findViewById(R.id.loader);
		        loaderView.setBackgroundDrawable(getResources().getDrawable(R.drawable.loading));
		        loaderView.setVisibility(View.VISIBLE);
		        
		        MyAnimationRoutine mar = new MyAnimationRoutine();
		        Timer timer = new Timer(false);
		        timer.schedule(mar, 1000);
		        
		        View v0 = findViewById(R.id.scrollview);
		        v0.setVisibility(View.GONE);
		        
		        View v1 = findViewById(R.id.buttonlayout);
		        v1.setVisibility(View.GONE);
	        }
	    });
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		NovoConviteActivity.adapter.notifyDataSetChanged();
	}
	
	public void addConvidado(Contato c) {
		NovoConviteActivity.adapter.addItem(c);
	}

	
	class MyAnimationRoutine extends TimerTask {
		MyAnimationRoutine() {
		}
		@Override
		public void run() {
			ImageView img = (ImageView)findViewById(R.id.loader);
			AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
			frameAnimation.start();
		}
	}
}
